<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="query">
                <el-form-item>
                    <el-input v-model="query.keyword" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="名字" width="120">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
            </el-table-column>
            <el-table-column prop="updateTime" label="修改时间" width="180">
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" width="120">
            </el-table-column>
            <el-table-column prop="parent.name" label="父部门" min-width="120">
            </el-table-column>
            <el-table-column prop="path" label="部门路径" width="120">
            </el-table-column>
            <el-table-column prop="state" label="状态" min-width="80">
                <template scope="scope">
                    <span v-if="scope.row.state == 0" style="color: red;">禁用</span>
                    <span v-if="scope.row.state == 1">启用</span>
                </template>
            </el-table-column>
            <el-table-column prop="intro" label="描述" width="120">
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--批量删除-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10"
                           :current-page="query.currentPage"
                           :total="pageInfo.total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑/新增界面-->
        <!--高版本的要用 :visible.sync="saveFormVisible"-->

                <el-form-item label="父部门">
                    <span class="demonstration"></span><el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
                    <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
                        <el-form-item label="名称">
                            <el-input v-model="saveForm.name" auto-complete="off"></el-input>
                        </el-form-item>

                        <el-form-item label="部门经理">
                            <el-select v-model="saveForm.manager.id" placeholder="请选择">
                                <el-option
                                    v-for="item in employees"
                                    :key="item.id"
                                    :label="item.username"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-cascader
                            v-model="saveForm.parent"
                            :options="deptTree"
                            :props="{
                            checkStrictly:true,
                            label:'name',
                            value:'id'
                       }"></el-cascader>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model="saveForm.state">
                        <el-radio class="radio" :label="1">正常</el-radio>
                        <el-radio class="radio" :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="描述">
                    <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="saveFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
            </div>
        </el-dialog>


    </section>
</template>

<script>

export default {
    data() {
        return {
            employees: [],
            deptTree: [],

            pageInfo: {
                rows: [],
                total: 0
            },

            sels: [],//列表选中列

            saveFormRules: {
                name: [
                    {required: true, message: '请输入姓名', trigger: 'blur'}
                ]
            },
            //编辑界面数据
            saveForm: {
                id: null,
                name: '',
                intro: '',
                manager: {
                    id: null
                },
                parent: {
                    id: null
                },
                state: null,
            },
            saveLoading: false,
            addLoading: false,
            saveFormVisible: false,//界面是否显示
            query: {
                currentPage: 1,
                PageSize: 10,
                keyword: ""
            }
        }
    },
    methods: {
        saveSubmit() {
            this.$confirm('要确定提交吗？', '提示', {}).then(() => {
                this.addLoading = true;
                //注意在此处级联下拉框传的值不是个对象，而是个数组，所以会报400，参数类型不匹配，要将其转换为对象
                let array = this.saveForm.parent
                if (array && array.length > 0) {
                    this.saveForm.parent = {id: array[array.length - 1]}; //注意在此处要用array.length不能用length
                } else {
                    this.saveForm.parent = null;
                }
                console.log(this.saveForm);
                this.$http.put("/department", this.saveForm)
                    .then(result => {
                        result = result.data;

                        if (result.success) {
                            this.$message({
                                message: '成功',
                                type: 'success'
                            });
                        }
                        this.saveFormVisible = false;
                        this.getDepartments();
                    })
                    .catch(result => {
                        this.$message({
                            message: '网络错误',
                            type: 'error'
                        });
                    });
            })
        },
        batchRemove() {
            var ids = this.sels.map(item => item.id);
            this.$confirm('确认删除该记录吗?', '提示', {
                type: 'warning'
            }).then(() => {//确认删除的按钮
                //加载页面设为true
                this.listLoading = true;

                //调用批量删除
                this.$http.patch("/department/", ids)
                    .then(result => {
                        //关闭加载框
                        this.listLoading = false;
                        //重新查询数据
                        this.search()
                        result = result.data
                        if (result.success) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });

                        } else {
                            this.$message({
                                message: '删除成功',
                                type: 'error'
                            });
                        }
                    })
                    .catch(result => {
                        this.$message({
                            message: '网络错误',
                            type: 'error'
                        });

                    }).catch(() => {//取消删除回调函数
                    this.$message('已取消删除');
                })
            })
        },
        handleDel(index, row) {

            this.$confirm('确认删除该记录吗?', '提示', {
                type: 'warning'
            }).then(() => {//确认删除的按钮
                //加载页面设为true
                this.listLoading = true;
                //获取删除数据id
                let id = row.id;

                //发送请求 "/dept/3"
                this.$http.delete("/department/" + id)
                    .then(result => {
                        //关闭加载框
                        this.listLoading = false;
                        //重新查询数据
                        this.search()
                        result = result.data
                        if (result.success) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });

                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                    })
            })
        },
        search() {
            this.query.currentPage = 1;
            this.getDepartments()
        },
        //点击页码的方法
        handleCurrentChange(val) {
            this.query.currentPage = val;
            this.getDepartments()
        },

        getDepartments() {

            this.$http.post("/department", this.query)
                .then(result => {
                    result = result.data;
                    this.pageInfo = result.data


                }).catch(result => {
                this.$message({
                    message: '网络错误',
                    type: 'error'
                });
            })
        },


        handleEdit: function (index, row) {
            this.saveFormVisible = true;
            this.saveForm = Object.assign({}, row);

            if (this.saveForm.parent == null) {
                this.saveForm.parent = {
                    id: null
                };
            } else {
                //如果没有父部门
                //部门回显
                var path = row.path;
                var idArray = path.split("/");
                //注意直接用split会出现['', '1','20']这种情况
                //需要循环遍历 去掉第一个和最后一个元素
                var temp = [];
                for (var i = 1; i < idArray.length - 1; i++) {
                    temp.push(parseInt(idArray[i])); //经过split()后得到的是一个字符串，而后端传参时是一个数字，所以要转换成数字
                }
                this.saveForm.parent = temp;
            }
            if (this.saveForm.manager == null) {
                this.saveForm.manager = {
                    id: null
                };
            }
            this.$http.get("/employee")
                .then(result => {
                    result = result.data;
                    this.employees = result.data;

                })
            this.getAllEmployee();
            this.getDeptTree();


        },
        //显示新增界面
        handleAdd: function () {

            this.saveFormVisible = true;
            //每次新增都要将表单数据初始化
            this.saveForm = {
                id: null,
                name: '',
                intro: '',
                manager: {
                    id: null
                },
                parent: {
                    id: null
                },
                state: null,
                children: []
            };
            this.deptTree = [];

            this.getAllEmployee();
            this.getDeptTree();
        },
        getAllEmployee: function () {
            this.$http.get("/employee")
                .then(result => {
                    result = result.data;
                    this.employees = result.data;

                })
        },
        getDeptTree: function () {
            this.$http.get("/department/tree")
                .then(result => {
                    result = result.data;
                    this.deptTree = result.data;

                })
        },
        selsChange: function (sels) {
            this.sels = sels;
        },

    },
    mounted() {
        this.getDepartments();
    }
}

</script>

<style scoped>

</style>